import { User, ApiResponse } from '../types';
import { STORAGE_KEYS, getStorageData, setStorageData, setStorageItem, removeStorageData } from '../utils/storage';

// 简单的密码加密函数（Base64 + 简单字符替换）
const encryptPassword = (password: string): string => {
  // 简单加密：Base64编码 + 字符替换
  const base64 = btoa(password);
  return base64.replace(/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 1));
};

// 生成UUID（简化版）
const generateUUID = (): string => {
  return 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// 邮箱格式验证
const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// ===== 注册相关 =====

export interface RegisterRequest {
  username: string;
  email: string;
  phone: string;
  password: string;
}

export interface RegisterResponse {
  user: Omit<User, 'password'>;
}

export const register = async (params: RegisterRequest): Promise<ApiResponse<RegisterResponse>> => {
  try {
    const { username, email, phone, password } = params;

    // 1. 参数验证
    if (!username || !email || !phone || !password) {
      return {
        code: 400,
        message: '所有字段都是必填的',
        data: null
      };
    }

    if (username.length < 2 || username.length > 20) {
      return {
        code: 400,
        message: '用户名长度必须在2-20个字符之间',
        data: null
      };
    }

    if (!validateEmail(email)) {
      return {
        code: 400,
        message: '邮箱格式不正确',
        data: null
      };
    }

    if (password.length < 6) {
      return {
        code: 400,
        message: '密码长度不能少于6位',
        data: null
      };
    }

    // 2. 获取现有用户数据
    const users = getStorageData<User>(STORAGE_KEYS.USERS);

    // 3. 唯一性检查
    const existingUser = users.find((user: User) =>
      user.username === username ||
      user.email === email ||
      user.phone === phone
    );

    if (existingUser) {
      if (existingUser.username === username) {
        return {
          code: 409,
          message: '用户名已存在',
          data: null
        };
      }
      if (existingUser.email === email) {
        return {
          code: 409,
          message: '邮箱已被注册',
          data: null
        };
      }
      if (existingUser.phone === phone) {
        return {
          code: 409,
          message: '手机号已被注册',
          data: null
        };
      }
    }

    // 4. 创建新用户
    const now = new Date().toISOString();
    const newUser: User = {
      id: generateUUID(),
      username,
      email,
      phone,
      password: encryptPassword(password), // 加密密码
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`,
      isAdmin: false,
      isBanned: false,
      createdAt: now,
      updatedAt: now
    };

    // 5. 保存到localStorage
    const updatedUsers = [...users, newUser];
    setStorageData(STORAGE_KEYS.USERS, updatedUsers);

    // 6. 创建返回用户信息（不包含密码）
    const userInfo: Omit<User, 'password'> = {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      phone: newUser.phone,
      avatar: newUser.avatar,
      isAdmin: newUser.isAdmin,
      isBanned: newUser.isBanned,
      createdAt: newUser.createdAt,
      updatedAt: newUser.updatedAt
    };

    // 7. 自动登录 - 设置当前用户
    setStorageItem(STORAGE_KEYS.CURRENT_USER, userInfo);

    // 8. 返回结果
    return {
      code: 200,
      message: '注册成功',
      data: {
        user: userInfo
      }
    };

  } catch (error) {
    console.error('注册失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 登录相关 =====

export interface LoginRequest {
  usernameOrEmail: string; // 支持用户名或邮箱登录
  password: string;
}

export interface LoginResponse {
  user: Omit<User, 'password'>;
}

export const login = async (params: LoginRequest): Promise<ApiResponse<LoginResponse>> => {
  try {
    const { usernameOrEmail, password } = params;

    // 1. 参数验证
    if (!usernameOrEmail || !password) {
      return {
        code: 400,
        message: '用户名/邮箱和密码都是必填的',
        data: null
      };
    }

    // 2. 获取现有用户数据
    const users = getStorageData<User>(STORAGE_KEYS.USERS);

    // 3. 查找用户（支持用户名或邮箱登录）
    const user = users.find((u: User) =>
      u.username === usernameOrEmail || u.email === usernameOrEmail
    );

    if (!user) {
      return {
        code: 404,
        message: '用户不存在',
        data: null
      };
    }

    // 4. 验证密码（对输入密码进行同样的加密，然后比较）
    const encryptedInputPassword = encryptPassword(password);
    if (encryptedInputPassword !== user.password) {
      return {
        code: 401,
        message: '密码错误',
        data: null
      };
    }

    // 5. 检查用户状态
    if (user.isBanned) {
      return {
        code: 403,
        message: '账号已被封禁，请联系管理员',
        data: null
      };
    }

    // 6. 登录成功，创建用户信息（不包含密码）
    const userInfo: Omit<User, 'password'> = {
      id: user.id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      avatar: user.avatar,
      isAdmin: user.isAdmin,
      isBanned: user.isBanned,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt
    };

    // 7. 设置当前登录用户
    setStorageItem(STORAGE_KEYS.CURRENT_USER, userInfo);

    // 8. 返回结果
    return {
      code: 200,
      message: '登录成功',
      data: {
        user: userInfo
      }
    };

  } catch (error) {
    console.error('登录失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 登出相关 =====

export const logout = async (): Promise<ApiResponse<null>> => {
  try {
    // 清除当前用户信息
    removeStorageData(STORAGE_KEYS.CURRENT_USER);

    return {
      code: 200,
      message: '登出成功',
      data: null
    };

  } catch (error) {
    console.error('登出失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};